package com.kalvan.client.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.kalvan.client.exception.BizException;
import com.kalvan.client.exception.ReturnCode;
import com.kalvan.client.system.SystemUtil;
import com.kalvan.client.constant.CommonReturnCode;
import lombok.Getter;

import javax.validation.constraints.NotBlank;

/**
 * 接口标准响应报文
 *
 * @author chenliang
 */
@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Response<T> implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * 系统编号
     * 默认使用application-name
     */
    @NotBlank
    private String system;
    /**
     * 返回码
     * 具体业务状态需要再解析data的数据
     */
    @NotBlank
    private String code;

    /**
     * 返回描述
     *
     * @see ReturnCode
     */
    @NotBlank
    private String desc;

    /**
     * 返回数据对象
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    private Response() {
    }

    /**
     * @param code 返回码
     * @param desc 返回描述
     * @return 返回结果对象
     */
    public static Response buildResult(String code, String desc) {
        Response response = new Response();
        response.setSystem(SystemUtil.constants != null ? SystemUtil.constants.getName() : null);
        response.setCode(code);
        response.setDesc(desc);
        return response;
    }

    /**
     * 根据返回码解析返回对象
     *
     * @param returnCode 返回码对象
     * @return 返回结果对象
     */
    public static Response buildResult(ReturnCode returnCode) {
        return buildResult(returnCode.getCode(), returnCode.getDesc());
    }

    /**
     * 根据biz异常解析返回对象
     *
     * @param exception bizException
     * @return 返回结果对象
     */
    public static Response buildResult(BizException exception) {
        return buildResult(exception.getCode(), exception.getDesc());
    }

    /**
     * 返回处理成功结果,默认使用0000
     *
     * @return 返回结果对象
     */
    public static Response buildSuccess() {
        return buildResult(CommonReturnCode.SUCCESS);
    }

    /**
     * 是否返回成功业务码,默认使用0000
     *
     * @return true /false
     */
    public boolean success() {
        return CommonReturnCode.SUCCESS.getCode().equals(code);
    }

    public Response setSystem(String system) {
        this.system = system;
        return this;
    }

    public Response setCode(String code) {
        this.code = code;
        return this;
    }

    public Response setDesc(String desc) {
        this.desc = desc;
        return this;
    }

    public Response setData(T data) {
        this.data = data;
        return this;
    }

    @Override
    public String toString() {
        return "Response{" +
                "system='" + system + '\'' +
                ", code='" + code + '\'' +
                ", desc='" + desc + '\'' +
                ", data=" + data +
                '}';
    }
}
